package com.yiyahui.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yiyahui.framework.config.properties.SMSPropertis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * SMS工具类
 * 
 * @author mike
 */
public class SMSUtils {

    private static final Logger logger = LoggerFactory.getLogger(SMSUtils.class);

    // sms属性
    private static SMSPropertis smsPropertis;

    public SMSPropertis getSMSPropertis() {
        return SMSUtils.smsPropertis;
    }

    public void setSMSPropertis(SMSPropertis smsPropertis) {
        SMSUtils.smsPropertis = smsPropertis;
    }

    // 获取oss相关token，使用oss的arnrole
    public static SendSmsResponse sendSms(String phoneNumbers, String shopName, String templateCode,
            String templateParam) {
        SendSmsResponse result = null;
        // 可自助调整超时时间
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            IClientProfile profile = DefaultProfile.getProfile(smsPropertis.getRegionId(),
                    smsPropertis.getAccessKeyId(), smsPropertis.getAccessKeySecret());
            DefaultProfile.addEndpoint(smsPropertis.getRegionId(), smsPropertis.getRegionId(), "Dysmsapi",
                    "dysmsapi.aliyuncs.com");
            IAcsClient client = new DefaultAcsClient(profile);

            SendSmsRequest request = new SendSmsRequest();
            request.setActionName("SendSms");
            request.setPhoneNumbers(phoneNumbers);
            request.setSignName("咿呀口腔" + shopName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam(templateParam);
            request.setOutId("yiya");
            result = client.getAcsResponse(request);
            if ("ok".equalsIgnoreCase(result.getCode())) {
                result.setCode("200");
            } else {
                result.setCode("205");
            }
        } catch (ServerException e) {
            result = new SendSmsResponse();
            result.setCode(e.getErrCode());
            result.setMessage(e.getErrMsg());
            e.printStackTrace();
        } catch (ClientException e) {
            result = new SendSmsResponse();
            result.setCode(e.getErrCode());
            result.setMessage(e.getErrMsg());
            e.printStackTrace();
        }
        return result;
    }

}
